package com.gg.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.comet.CometEvent;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class Notifier extends HttpServlet implements org.apache.catalina.comet.CometProcessor {
	
	private ConcurrentUsers concurrentUsers;

    /**
     * Process the given Comet event.
     * 
     * @param event The Comet event that will be processed
     * @throws IOException
     * @throws ServletException
     */
    public void event(CometEvent event)
        throws IOException, ServletException {
    	
    	ServletContext context = getServletContext();
		WebApplicationContext webAppContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
		concurrentUsers = (ConcurrentUsers) webAppContext.getBean("concurrentUsers");
		
        HttpServletRequest request = event.getHttpServletRequest();
        HttpServletResponse response = event.getHttpServletResponse();
        
        
        if (event.getEventType() == CometEvent.EventType.BEGIN) {
        	String userId = request.getParameter("userId");
        	
            log("Begin for userId: " + userId);
            PrintWriter writer = response.getWriter();
            
            readyForWrite(writer);
            
            concurrentUsers.add(new ConcurrentUser(userId, response));
        } else if (event.getEventType() == CometEvent.EventType.ERROR) {
            log("Error for session: " + request.getSession(true).getId());
            
            event.close();
        } else if (event.getEventType() == CometEvent.EventType.END) {
            log("End for session: " + request.getSession(true).getId());
            PrintWriter writer = response.getWriter();
            writer.println("</body></html>");
            event.close();
        } else if (event.getEventType() == CometEvent.EventType.READ) {
            
        }
    }

	private void readyForWrite(PrintWriter writer) {
		writer.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">");
		writer.println("<head><title>JSP Chat</title></head><body bgcolor=\"#FFFFFF\">");
		writer.println("<!-- ");
		for (int i = 0; i < 100; i++) {
			writer.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
		}
		writer.println("-->");
		writer.flush();
	}
}